package com.itheima.web.filters;

import com.itheima.domain.system.Module;
import com.itheima.domain.system.User;
import com.itheima.service.system.impl.ModuleServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 字符集过滤器
 *
 * @author 黑马程序员
 * @Company http://www.itheima.com
 */
@WebFilter(value = "/*")
public class AuthorFilter implements Filter {
    private List<String> list;
    private FilterConfig filterConfig;


    /**
     * 初始化方法，获取过滤器的配置对象
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        list = new ArrayList<>();
        list.add("/");
        list.add(".css");
        list.add(".js");
        list.add("jpg");
        list.add("ico");
        list.add("login.jsp");
        list.add("index.jsp");
        list.add("unauthorized.jsp");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request;
        HttpServletResponse response;
        HttpSession session;
        String curl;
        try {
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) resp;
            session = request.getSession();
            User user = (User) session.getAttribute("loginUser");

            String queryString = request.getQueryString();
            String uri = request.getRequestURI();
//            System.out.println("过滤前 requestURI======  "+uri);
            for (String s : list) {
                if (uri.endsWith(s)) {
                    chain.doFilter(request, response);
                    return;
                }
            }
            if (
                    "/".equals(uri)
                            || queryString == null
                            || "operation=login".equals(queryString)
                            || "operation=logout".equals(queryString)
                            || "operation=home".equals(queryString)

            ) {
                chain.doFilter(request, response);
                return;
            }
            if (user == null) {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
                return;
            }
            curl = getCurl(user);
//// TODO
            if(queryString.indexOf("&")!=-1){
                queryString = queryString.substring(0, queryString.indexOf("&"));
            }
            String currentUri = uri.substring(1) + "?" + queryString;
//            System.out.println("当前访问的虚拟路径是: " + currentUri);
            if (curl.contains(currentUri)) {
                chain.doFilter(request, response);
                return;
            } else {
//                chain.doFilter(request, response);
//                System.out.println("拦截路径:   "+currentUri);
                response.sendRedirect(request.getContextPath()+"/unauthorized.jsp");
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 通过用户查询该用户可访问的uri
     *
     * @param user
     * @return
     */
    private String getCurl(User user) {
        ModuleServiceImpl moduleService = new ModuleServiceImpl();
        List<Module> moduleList = moduleService.findModuleByUserId(user.getId());
        StringBuilder sb = new StringBuilder();
        for (Module module : moduleList) {
            sb.append(module.getCurl()).append(",");
        }
        return sb.toString();
    }


    @Override
    public void destroy() {
        //可以做一些清理操作
    }
}
